linux多线程网页截图-python

上一篇中(linux多线程网页截图-shell),使用shell多进程对大量的网站截图,大大减少了截图的时间。但慢慢的也发现了这种方式的弊端:每个进程分配的网站数量是相等的,有些进程截图较快,有些较慢,个别进程在其它进程已经截图完成后,还要运行10多个小时才能把分配的网站截图完。
如何把现有的“平均分配”截图方式改成“能者多劳”呢?

刚好最近在学习python,而python可以很方便的支持多线程。找了些资料,使用threading+queue的方式实现了“能者多劳”的多线程截图方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#coding:utf-8
import threading,urllib2
import datetime,time
import Queue
import os

class Webshot(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue=queue

def run(self):
while True:
#如果队列为空,则退出,否则从队列中取出一条网址数据,并截图
if self.queue.empty():
break
host=self.queue.get().strip('\n')
shotcmd="DISPLAY=:0 cutycapt --url=http://"+host+" --max-wait=90000 --out="+host+".jpg"
os.system(shotcmd)
self.queue.task_done()
time.sleep(1)

def main():
queue=Queue.Queue()
f=file('domain.txt','r')

#往队列中填充数据
while True:
line=f.readline()
if len(line)==0:
break
queue.put(line)

#生成一个 threads pool, 并把队列传递给thread函数进行处理,这里开启10个线程并发
for i in range(0,10):
shot=Webshot(queue)
shot.start()

if __name__=="__main__":
main()

程序描述如下:
1、创建一个Queue.Queue() 的实例,将domain.txt里的网站列表存入到该队列中
2、for循环生成10个线程并发
3、将队列实例传递给线程类Webshot,后者是通过继承 threading.Thread 的方式创建的
4、每次从队列中取出一个项目,并使用该线程中的数据和 run 方法以执行相应的工作
5、在完成这项工作之后,使用 queue.task_done() 函数向任务已经完成的队列发送一个信号

参考:
Python:使用threading模块实现多线程(转)
http://bkeep.blog.163.com/blog/static/1234142902012112210717682/
http://fc-lamp.blog.163.com/blog/static/17456668720127221363513/
http://www.pythonclub.org/python-network-application/observer-spider
http://www.phpno.com/python-threading-2.html